"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.ChildrenMixin = ChildrenMixin;
exports.ParentMixin = ParentMixin;

var _vue = _interopRequireDefault(require("vue"));

function flattenVNodes(vnodes) {
    var result = [];

    function traverse(vnodes) {
        vnodes.forEach(function (vnode) {
            result.push(vnode);

            if (vnode.children) {
                traverse(vnode.children);
            }
        });
    }

    traverse(vnodes);
    return result;
}

function ChildrenMixin(_parent, options) {
    var _inject, _computed;

    if (options === void 0) {
        options = {};
    }

    var indexKey = options.indexKey || 'index';
    return _vue.default.extend({
        inject: (_inject = {}, _inject[_parent] = {
            default: null
        }, _inject),
        computed: (_computed = {
            parent: function parent() {
                if (this.disableBindRelation) {
                    return null;
                }

                return this[_parent];
            }
        }, _computed[indexKey] = function () {
            this.bindRelation();
            return this.parent.children.indexOf(this);
        }, _computed),
        mounted: function mounted() {
            this.bindRelation();
        },
        beforeDestroy: function beforeDestroy() {
            var _this = this;

            if (this.parent) {
                this.parent.children = this.parent.children.filter(function (item) {
                    return item !== _this;
                });
            }
        },
        methods: {
            bindRelation: function bindRelation() {
                if (!this.parent || this.parent.children.indexOf(this) !== -1) {
                    return;
                }

                var children = [].concat(this.parent.children, [this]);
                var vnodes = flattenVNodes(this.parent.slots());
                children.sort(function (a, b) {
                    return vnodes.indexOf(a.$vnode) - vnodes.indexOf(b.$vnode);
                });
                this.parent.children = children;
            }
        }
    });
}

function ParentMixin(parent) {
    return {
        provide: function provide() {
            var _ref;

            return _ref = {}, _ref[parent] = this, _ref;
        },
        data: function data() {
            return {
                children: []
            };
        }
    };
}